<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div
            class="flex items-center"
            style="display: flex; justify-content: space-between"
          >
            <div style="display: flex; align-items: center">
              <div>
                {{
                  route.query.readonly
                    ? "查看退库单信息"
                    : route.query.id
                    ? "编辑退库单信息"
                    : "新增退库单"
                }}
              </div>
              <el-tag
                v-if="route.query.code"
                :type="tagType"
                style="margin-left: 10px"
                >{{ route.query.code }}</el-tag
              >
            </div>
          </div>
        </template>
        <template #extra>
          <div>
            <el-button
              v-if="!readonly"
              :loading="btnLoading"
              class="button"
              type="primary"
              @click="handleSubmit"
            >
              保 存
            </el-button>
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="readonly"
              ref="cancellationRef"
              label-width="130px"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="退库机台" prop="machine_name">
                    <el-input
                      v-model="form.machine_name"
                      placeholder="请选择"
                      @click="visibleMachine = true"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="退库时间" prop="refundDate">
                    <el-date-picker
                      v-model="form.refundDate"
                      disabled
                      style="width: 100%"
                      type="datetime"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="退库人">
                    <el-input
                      v-model="form.createBy"
                      maxlength="30"
                      disabled
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.refundRemark"
                      type="textarea"
                      placeholder="请输入内容"
                      style="width: 100%"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>

      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="退库明细" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">退库明细</span>
          </template>
          <div>
            <el-button
              style="margin-bottom: 5px"
              :disabled="readonly || mesRefundDetailList.length == 1"
              type="primary"
              size="small"
              icon="Plus"
              @click="handleChoice"
              >从机台纸库选择</el-button
            >
            <el-table
              :data="mesRefundDetailList"
              style="width: 100%"
              :header-cell-class-name="must"
            >
              <el-table-column
                type="index"
                label="序号"
                width="60"
                align="center"
              />
              <el-table-column
                prop="type"
                label="类型"
                width="140"
                align="center"
              >
                <template #default="scope">
                  <dict-tag
                    :options="mes_paper_material"
                    :value="scope.row.type"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="code" label="纸张编码" align="center">
              </el-table-column>
              <el-table-column prop="name" label="纸张名称" align="center">
              </el-table-column>
              <el-table-column prop="specs" label="规格" align="center">
                <template #default="scope">
                  <dict-tag
                    :options="mes_paper_specs"
                    :value="scope.row.specs"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="brand" label="品牌" align="center">
                <template #default="scope">
                  <dict-tag
                    :options="mes_paper_brand"
                    :value="scope.row.brand"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="weight" label="定量" align="center">
              </el-table-column>
              <el-table-column prop="longWide" label="幅宽" align="center">
              </el-table-column>
              <el-table-column prop="unit" label="单位" align="center">
                <template #default="scope">
                  <dict-tag :options="mes_paper_unit" :value="scope.row.unit" />
                </template>
              </el-table-column>
              <el-table-column
                prop="total"
                label="数量"
                width="120"
                align="center"
              >
                <template #default="{ row }">
                  <el-input v-model="row.total" :disabled="readonly"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="detailRemark"
                label="备注"
                width="120"
                align="center"
              >
                <template #default="{ row }">
                  <el-input
                    v-model="row.refundRemark"
                    :disabled="readonly"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" align="center">
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    :disabled="readonly"
                    size="small"
                    @click="handleDel(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <SearchWorkBench
      :visible="visibleMachine"
      @changeUpdate="changeMachineData"
      @cancel="
        () => {
          visibleMachine = false;
        }
      "
    ></SearchWorkBench>
    <!-- <SearchPaperCoding :visible="visiblePaper" @changeUpdate="changePaperData" @cancel="() => { visiblePaper = false }">
        </SearchPaperCoding> -->
    <benchPaper
      :visible="visiblePaper"
      :outMachineid="form.refundMachineid"
      @changeUpdate="changePaperData"
      @cancel="
        () => {
          visiblePaper = false;
        }
      "
    >
    </benchPaper>
  </div>
</template>

<script setup>
import { computed } from "vue";
import SearchWorkBench from "@/components/SearchWorkBench";
import benchPaper from "./benchPaper";
// import SearchPaperCoding from '@/components/SearchPaperCoding'
import useTagsViewStore from "@/store/modules/tagsView";
const tagsViewStore = useTagsViewStore();
import {
  addRefund,
  getIdRefund,
  updateRefund,
} from "@/api/storage/cancellation.js";

const { proxy } = getCurrentInstance();
const { mes_paper_material, mes_paper_specs, mes_paper_unit, mes_paper_brand } =
  proxy.useDict(
    "mes_paper_material",
    "mes_paper_specs",
    "mes_paper_unit",
    "mes_paper_brand"
  );
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";
const router = useRouter();
const route = useRoute();
const activeNames = ["1"];
const btnLoading = ref(false);
const cancellationRef = ref(null);
const mesRefundDetailList = ref([]);
const readonly = ref(false);
const visiblePaper = ref(false);
const visibleMachine = ref(false);
const data = reactive({
  form: {},
  rules: {
    machine_name: [
      { required: true, message: "请选择退库机台", trigger: "change" },
    ],
  },
});
const { form, rules } = toRefs(data);
const userInfo = useUserStore();
const tagType = computed(() => {
  return route.query.status == 1 ? "" : "danger";
});
readonly.value = route.query.readonly;

if (route.query.id) {
  getIdRefund(route.query.id).then((response) => {
    form.value = response.data;
    form.value.machine_name = response.data.machine_name;
    form.value.refundMachineid = response.data.refundMachineid;
    // mesRefundDetailList.value.push(response.data.mesRefundDetailList[0].mesPaper)
    const mesPaper = response.data.mesRefundDetailList[0]?.mesPaper;

    if (mesPaper) {
      mesPaper.type = response.data.mesRefundDetailList[0].type;
      mesPaper.total = response.data.mesRefundDetailList[0].total;
      mesPaper.remark = response.data.mesRefundDetailList[0].remark;
      mesRefundDetailList.value.push(mesPaper);
    }
  });
} else {
  form.value = {};
  form.value.createBy = userInfo.name;
  getCurrentTime();
}
function getCurrentTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  return (form.value.refundDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);
}

const handleChoice = () => {
  if (!form.value.refundMachineid) {
    ElMessage({
      message: "请先选择退库机台",
      type: "warning",
    });
    return;
  }
  visiblePaper.value = true;
};
const changeMachineData = (row) => {
  console.log("row", row);
  form.value.machine_name = row.machineName;
  form.value.refundMachineid = row.pid;
  visibleMachine.value = false;
};

const changePaperData = (row) => {
  console.log("row", row);
  row.type = row.material;
  mesRefundDetailList.value.push(row);
  row.paperid = row.id;
  visiblePaper.value = false;
};
const handleDel = (row) => {
  const index = mesRefundDetailList.value.indexOf(row);
  if (index !== -1) {
    mesRefundDetailList.value.splice(index, 1);
  }
};
const must = (obj) => {
  let mustColumns = [];
  mustColumns = [11];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
//保存
const handleSubmit = () => {
  btnLoading.value = true;
  if (!mesRefundDetailList.value[0].total) {
    btnLoading.value = false;
    ElMessage({
      message: "请填写退库明细第一条的数量",
      type: "warning",
    });
    return;
  }
  cancellationRef.value.validate((valid) => {
    if (valid) {
      const formData = form.value;
      formData.mesRefundDetailList = mesRefundDetailList.value;
      if (formData.id) {
        updateRefund(formData)
          .then((response) => {
            if (response.code === 200) {
              ElMessage({
                message: "编辑成功",
                type: "success",
              });
              goBack();
            }
          })
          .catch((err) => {
            btnLoading.value = false;
          });
      } else {
        formData.status = 1;
        addRefund(formData)
          .then((response) => {
            if (response.code === 200) {
              ElMessage({
                message: "新增成功",
                type: "success",
              });
              goBack();
            }
          })
          .catch((err) => {
            btnLoading.value = false;
          });
      }
    } else {
      btnLoading.value = false;
    }
  });
};

//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  router.go(-1);
  // router.push('/storage/cancellation')
};
</script>

<style lang="scss" scoped>
:deep(.el-table th.must div:before) {
  content: "*";
  color: #ff1818;
}
</style>